import { cloneDeep } from 'lodash-es'

// 根据routes转化为menu对象
export function transformRouteToMenu(routes): any[] {
  let cloneRoutes = cloneDeep(routes)

  function recurseHandleRoute(arr) {
    arr.forEach((item) => {
      if (item.children && item.children.length) {
        item.children.forEach((cItem) => {
          // 只处理meta.type为menu和iframe的路由，meta.type为link的不能处理
          if (cItem.meta.type !== 'link') {
            cItem.path = `${item.path}/${cItem.path}`
          }
        })

        recurseHandleRoute(item.children)
      }
    })
  }

  // 处理meta.hideMenu=true的情况，对menu菜单进行过滤
  function recurseFilterMenu(menuList) {
    return menuList.filter((menu) => {
      if (!menu?.meta?.hideMenu) {
        if (menu.children && menu.children.length) {
          menu.children = recurseFilterMenu(menu.children)
        }
        return true
      }
    })
  }

  recurseHandleRoute(cloneRoutes)

  cloneRoutes = recurseFilterMenu(cloneRoutes)

  return cloneDeep(cloneRoutes)
}

// 从menuList中取出所有的iframe
export function getAllIframes(menuList): any[] {
  const cloneMenuList = cloneDeep(menuList)

  const iframeList = [] as any[]

  function getIframes(list) {
    list.forEach((item) => {
      if (item.meta.type === 'iframe') {
        iframeList.push(item)
      }

      if (item.children && item.children.length) {
        getIframes(item.children)
      }
    })
  }

  getIframes(cloneMenuList)

  return iframeList
}
